package kevin.newmybatis.mybatis.handler;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 处理ResultSet
 */
public class ResultSetHandler {


    /**
     * 实现单条信息查询
     * @param preparedStatement
     * @param calssType
     * @param <T>
     * @return
     */
    public <T> T getResult(PreparedStatement preparedStatement, Class<T> calssType) {
        T object = null;
        try {
            object = calssType.newInstance();
            ResultSet resultSet = preparedStatement.executeQuery();


            if (resultSet.next()) {
                Field[] fields = calssType.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    field.set(object, resultSet.getObject(field.getName()));
                }

                return (T) object;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;

    }

}
